<template>
	<div>
		<div class="main">
			<!--列表 -->
			<div style="flex: 1">
				<a-table :columns="childrenColums" :data-source="childrenList" bordered :loading="loading"
					:pagination="pagination" @change="handleTableChange" :customRow="customRow">
					<!-- :scroll="{ y: 540, x: 'auto' }" -->

					<template #service="{ record, index }">
						<div class="service">
							<div class="name" :class="index == serviceAct ? 'name-act' : ''"
								@click="getChildrenList(record, index)">
								{{ record.name }}
							</div>
							<div class="edit" danger @click="editService(record, 1)">
								<EditTwoTone />
							</div>
							<div class="del" danger @click="delService(record.key)">
								<DeleteTwoTone twoToneColor="#f5222d" />
							</div>
						</div>
					</template>
					<template #imgUrl="{ record }">
						<div v-if="record.imgUrl">
							<img style="width: 60px; height: 60px" :src="record.imgUrl" alt="" />
						</div>
					</template>
					<template #operation="{ record }">
						<a-button type="link" @click="editService(record, 0)">编辑</a-button>
						<a-button type="link" @click="delService(record.id, 0)">
							删除</a-button>
					</template>
				</a-table>
			</div>
		</div>

		<a-modal :visible="visible" :footer="null" width="90%" @cancel="cancel">
			<!-- 新增服务项 -->
			<a-form ref="modalRef" :rules="rules" :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol">
				<a-form-item label="分类名称" name="name">
					<a-input placeholder="请输入分类名称" v-model:value="modalForm.name" maxlength="6"></a-input>
				</a-form-item>
				<a-form-item label="跳转链接" name="jumpUrl">
					<a-input placeholder="请输入分类名称" v-model:value="modalForm.jumpUrl"></a-input>
				</a-form-item>

				<a-form-item label="三级分类图标" name="imgUrl">
					<a-upload v-model:file-list="fileList" list-type="picture-card" class="avatar-uploader"
						:maxCount="1" :customRequest="uploadImage" :before-upload="beforeUpload" @change="handleChange">
						<div v-if="fileList.length < 1" class="ant-upload-text">
							<plus-outlined />
						</div>
					</a-upload>
					<!-- <span>*等待ui设计稿</span> -->
				</a-form-item>
			</a-form>

			<a-divider></a-divider>
			<!-- 确定和取消 -->
			<a-row>
				<a-col :span="4" :offset="6">
					<a-button type="primary" size="large" @click="cancel">关闭</a-button>
				</a-col>
				<a-col :span="4" :offset="2">
					<a-button type="primary" size="large" @click="save">保存</a-button>
				</a-col>
			</a-row>
		</a-modal>
	</div>
</template>
<script>
	import {
		reactive,
		ref,
		computed,
		createVNode,
		toRefs,
		onMounted
	} from "vue";
	import {
		useRoute
	} from "vue-router";
	import {
		ExclamationCircleOutlined,
		EditTwoTone,
		DeleteTwoTone,
		PlusOutlined,
	} from "@ant-design/icons-vue";
	import {
		Modal,
		message
	} from "ant-design-vue";
	import * as api from "@/api/service/index.js";
	import UploadImage from "@/components/common/UploadImage.vue";
	import { useModal } from "@/hooks"
	export default {
		setup() {
			const route = useRoute();
			const serviceAct = ref(0);
			const data = reactive({
				name: "",
				sortShow: false,
				sortList: [],
				// 一级分类的id
				id: 0,
				serviceList: [],
				childrenList: [],
				loading: true, //表格加载
				// headerTitle: "",
				isEdit: "", //编辑or新增
				type: 2, //类型
				visible: false,
				activeKey: "0",
				uploadLoading: false,
				imageUrl: "",
				modalForm1: {},
				modalForm: {
					detail: ""
				},
				value: "",
				fileList: [],
				detail: "哈哈哈",
				uploadRef: "",
				columns: [{
						title: "套餐名称",
						dataIndex: "sonServiceName",
						width: "30%",
					},
					{
						title: "套餐价格(元)",
						dataIndex: "price",
					},
					{
						title: "套餐时长(分钟)",
						dataIndex: "duration",
					},
					{
						title: "服务次数",
						dataIndex: "serviceNum",
					},
					{
						title: "操作",
						dataIndex: "operation",
					},
				],
				flowPop: false,
				dataSource: [],
				obj: {},
				// 修改当前套餐的index
				flag: -1,
				serviceDetails: [],
			});
			const modalRef = ref("");
			const modalRef1 = ref("");
			const editor = ref("");
			const editor1 = ref("");

			// 分页器
			const page = reactive({
				current: 1,
				pageSize: 10,
				total: 0,
			});
			onMounted(() => {
				if (route.query.id) {
					data.id = route.query.id;
					initChildrenList();
				}
			});
			const childrenColums = [{
					title: "序号",
					dataIndex: "id",
					className: "table",
					align: "center",
				},
				{
					title: "分类名称",
					dataIndex: "name",
					className: "table",
					align: "center",
				},
				{
					title: "三级分类图标",
					dataIndex: "imgUrl",
					className: "table",
					align: "center",
					slots: {
						customRender: "imgUrl",
					},
				},
				{
					title: "创建时间",
					dataIndex: "createdAt",
					className: "table",
					align: "center",
					ellipsis: true,
				},
				{
					title: "操作",
					dataIndex: "operation",
					className: "table",
					align: "center",
					fixed: "right",
					slots: {
						customRender: "operation",
					},
				},
			];

			// 分页器
			const pagination = computed(() => ({
				current: page.current,
				pageSize: page.pageSize,
				pageSizeOptions: ["10", "20", "30"],
				showTotal: (total, range) => {
					return "共" + total + "条";
				},
				total: page.total,
				showQuickJumper: true,
				showSizeChanger: true,
			}));

			// 分页器改变的时候
			const handleTableChange = (pagination, filters, sorter) => {
				page.current = pagination.current;
				page.pageSize = pagination.pageSize;
				// 请求列表接口
				initChildrenList();
			};
			const handleSave = () => {
				let arr = data.sortList.map((m) => {
					return {
						id: m.id
					};
				});
				api.saveSort({
					servicesTypesList: [...arr]
				}).then((r) => {
					if (r.success) {
						message.success("操作成功");
						data.sortShow = false;
						initChildrenList();
					}
				});
			};
			// 编辑服务和服务项目
			const editService = async (item, type) => {
				data.isEdit = 1;
				data.modalForm = {
					...item,
					jumpUrl: item.jumpLink
				};
				// data.fileList = [{ url: item.imgUrl }];
				data.fileList = item.imgUrl ? [{
					url: item.imgUrl
				}] : [];
				console.log(data.fileList, "data.fileList");
				data.visible = true;
			};
			// 删除服务和服务项目
			const delService = (key, type) => {
				console.log("删除", key);
				const {closeModal} = useModal.confirm({
					icon: () => createVNode(ExclamationCircleOutlined),
					content: () =>
						createVNode(
							"div", {
								style: "color:red;"
							},
							"确定要删除当前服务类型吗"
						),
					okType: "danger",
					onOk: async () => {
						let res = await api.deleteThreeLevelService({
							id: key
						});
						if (res.success) {
							message.success("删除成功");
							initChildrenList();
							closeModal()
						}
					},
					
					class: "test",
				});
			};

			const getChildrenList = (e, index) => {
				if (serviceAct.value == index) return;
				serviceAct.value = index;
				page.current = 1;
				initChildrenList();
			};

    const headerTitle = computed(() => {
      let title = data.isEdit == 1 ? "编辑" : "新增";
      return title;
    });
    const rules = {
      name: [
        { required: true, message: "请输入分类名称!" },
        // { min: 4, message: "请输入4-6个字符" },
      ],
    };
    const cancel1 = () => {
      data.sortShow = false;
      data.sortList = [];
      initChildrenList();
    };
    const cancel = () => {
      console.log("点击了关闭");
      //置空
      data.modalForm1 = {};
      data.modalForm = {};
      data.dataSource = [];
      data.dataFlow = [];
      data.visible = false;
    };

			const uploadImage = async (file) => {
				let formData = new FormData();
				formData.append("file", file.file);
				let res = await api.uploadPicture(formData, "service");
				console.log(res, "上传的图片");
				if (res.success) {
					data.fileList = [{
						uid: file.file.uid,
						url: res.object,
						status: "done",
						name: file.file.name,
					}, ];
				}
			};

			const previewVisible = ref(false);
			const previewImage = ref("");
			const imageUrl = ref("");

			function getBase64(img, callback) {
				const reader = new FileReader();
				reader.addEventListener("load", () => callback(reader.result));
				reader.readAsDataURL(img);
			}
			const handleCancel = () => {
				previewVisible.value = false;
			};

			const handlePreview = async (file) => {
				// console.log(file, "上传图片这是");
				if (!file.url && !file.preview) {
					file.preview = await getBase64(file.originFileObj);
				}
				previewImage.value = file.url || file.preview;
				previewVisible.value = true;
			};
			const handleChange = (info) => {
				if (info.file.status === "uploading") {
					data.uploadLoading = true;
					return;
				}

				if (info.file.status === "done") {
					// Get this url from response in real world.
					getBase64(info.file.originFileObj, (base64Url) => {
						data.imageUrl = base64Url;
						data.uploadLoading = false;
					});
				}

				if (info.file.status === "error") {
					data.uploadLoading = false;
					message.error("上传错误");
				}
			};

			const beforeUpload = (file) => {
				const isJpgOrPng =
					file.type === "image/psd" ||
					file.type === "image/bmp" ||
					file.type === "image/jpg" ||
					file.type === "image/png" ||
					file.type === "image/gif" ||
					file.type === "image/jpeg";

				if (!isJpgOrPng) {
					message.error("图片格式不正确!");
				}
				const isLt2M = file.size / 1024 / 1024 < 5;

				if (!isLt2M) {
					message.error("图片大小不超过5MB!");
				}
				return isJpgOrPng && isLt2M;
			};

			// 保存,根据tab的绑定的key值判断编辑服务项目还是类别
			const save = () => {
				console.log(data.modalForm, "data.modalForm");
				let ref = data.activeKey == "0" ? modalRef : modalRef1;
				ref.value
					.validate()
					.then(async () => {
						if (data.fileList.length == 0) {
							data.modalForm.imgUrl = "";
						} else {
							data.modalForm.imgUrl = data.fileList[0].url;
						}
						console.log(data.modalForm.imgUrl, "data.modalForm.imgUrl");
						let obj = {
							...data.modalForm,
							parentId: data.id,
						};
						let res = await api.editOraddThreeLevelServiceType(obj);
						console.log(obj, "obj");
						if (res.success) {
							message.success("操作成功");
							data.visible = false;
							data.modalForm = {};
							initChildrenList();
						}
					})
					.catch((error) => {
						console.log("error", error);
					});
			};

			// 初始化服务列表
			async function initChildrenList() {
				if (route.query.name == "上门护理") {
					//上门护理不传id
					let obj1 = {
						pageNum: page.current,
						pageSize: page.pageSize,
						threeTypeId: "1",
					};
					let res = await api.threeLevelServiceTypeList(obj1);
					if (res.success) {
						data.childrenList = res.object.list;
						page.total = res.object.total;
						data.loading = false;
					}
				} else {
					let obj = {
						pageNum: page.current,
						pageSize: page.pageSize,
						id: data.id,
						threeTypeId: "1",
					};
					let res1 = await api.threeLevelServiceTypeList(obj);
					if (res1.success) {
						data.childrenList = res1.object.list;
						page.total = res1.object.total;
						data.loading = false;
					}
				}
			}
			const closeFlowPop = () => {
				data.flowPop = false;
				formRef.value.resetFields();
				dynamicValidateForm.serveName = "";
				dynamicValidateForm.users = [];
				dynamicValidateForm.id = [];
				dynamicValidateForm.isEdit = false;
			};

			const methods = {
				handleFlowPop() {
					data.flowPop = true;
				},
				handleAdd() {
					let idEdit = data.dataSource.some((i) => i.isEdit);
					if (idEdit) return;
					const newData = {
						key: ``,
						sonServiceName: ``,
						price: "",
						duration: "",
						serviceNum: "",
						operation: "",
						isEdit: true,
					};
					data.dataSource.push(newData);
				},
				handleEdit(ind) {
					data.flag = ind;
					// data.dataSource = data.dataSource.map(i => i.isEdit=false)
					data.dataSource[ind].isEdit = true;
					data.obj = {
						...data.dataSource[ind],
						isEdit: true
					};
				},
				handleDelete(ind) {
					data.dataSource.splice(ind, 1);
				},
			};
			// 工作流程
			const formRef = ref();
			const dynamicValidateForm = reactive({
				serveName: "",
				users: [],
				id: Date.now(),
			});
			return {
				formRef,
				dynamicValidateForm,
				...toRefs(data),
				...methods,
				childrenColums,
				pagination,
				serviceAct,
				handleSave,
				delService,
				editService,
				getChildrenList,
				handleTableChange,
				modalRef,
				imageUrl,
				labelCol: {
					style: {
						width: "150px",
						fontWeight: "bold"
					}
				},
				wrapperCol: {
					span: 12
				},
				previewVisible,
				previewImage,
				rules,
				modalRef1,
				handleCancel,
				handlePreview,
				handleChange,
				beforeUpload,
				save,
				cancel,
				cancel1,
				headerTitle,
				uploadImage,
				editor,
				editor1,
				closeFlowPop,
			};
		},

		components: {
			EditTwoTone,
			DeleteTwoTone,
			PlusOutlined,
		},
	};
</script>

<style scoped lang="less">
	.flex {
		display: flex;
		align-items: center;
	}

	.main {
		display: flex;
		margin-top: 30px;
	}

	.ant-upload-text {
		padding: 40px;
		display: flex;
	}

	.service {
		display: flex;
		justify-content: space-between;

		// 服务激活样式
		.name-act {
			color: #2a9d8f;
			font-weight: bolder;
		}

		.edit {
			padding: 0px 5px;
		}
	}

	.process {
		display: flex;

		.process-list {
			margin-right: 20px;
			display: flex;
			flex-direction: column;

			.num {
				width: 50px;
				height: 50px;
				border: solid 1px #999;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 18px;
			}

			.img {
				width: 50px;
				height: 50px;
				background-color: tomato;
				margin: 10px 0px;
			}

			.title {}
		}
	}

	.table {
		width: 100%;
		border-left: 1px solid #eee;
		border-top: 1px solid #eee;

		tr {
			td {
				input {
					border: 1px solid #aaa !important;
					width: 97% !important;
				}
			}

			th,
			td {
				text-align: center;
				border-right: 1px solid #eee;
				border-bottom: 1px solid #eee;
			}
		}
	}

	.myhtml {
		width: 160%;
		height: 140%;
		padding: 8rpx 6rpx;
		border: 2rpx solid #d9d9d9;
		border-radius: 2px;
		color: rgba(0, 0, 0, 0.25);
		background: #f5f5f5;
	}

	.flowWrap {
		.f_item {
			padding: 20px 0 !important;
		}

		.left {
			font-size: 16px;
			font-weight: 500;
			margin-bottom: 22px;
			margin-right: 30px;

			.spot {
				color: red;
			}
		}
	}

	.ant-form-item {
		margin-bottom: 0px;
	}
</style>